package cn.stylefeng.guns.modular.leaveinfo.service;


import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.leaveapproval.service.LeaveApprovalService;
import cn.stylefeng.guns.modular.leaveinfo.mapper.LeaveInfoMapper;
import cn.stylefeng.guns.modular.leaveinfo.model.LeaveInfoParam;
import cn.stylefeng.guns.modular.leaveinfo.model.LeaveInfoResult;
import cn.stylefeng.guns.modular.studentmanage.service.StuManageService;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveApprovalPO;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveInfoPO;
import cn.stylefeng.guns.sys.modular.system.entity.LeaveUserPO;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LeaveInfoService extends ServiceImpl<LeaveInfoMapper, LeaveInfoPO> {
    @Autowired
    private LeaveInfoMapper leaveInfoMapper;

    @Autowired
    private LeaveApprovalService leaveApprovalService;

    @Autowired
    private StuManageService stuManageService;


    public Long saveUser(LeaveInfoPO leaveInfoPO) {
        Long id = leaveInfoMapper.insertAndGetId(leaveInfoPO);
        return id;
    }


    public List<LeaveInfoResult> getLeaveInfoList(Page page, LeaveInfoParam leaveInfoParam) {
        Long userId = LoginContextHolder.getContext().getUserId();
        //第一种情况
        //辅导员级别登录也就是一级审批人，只要是状态为0的都把数据刷出来
        List<LeaveInfoPO> list = null;
        List<LeaveInfoPO> list2 = null;
        list = leaveInfoMapper.list(page, leaveInfoParam.getCondition(), userId, null, null, 0);
        //第二种情况
        //院系级别登录也就是二级审批人，只要是状态为2的都把数据刷出来
        if (null == list || 0 == list.size()) {
            list2 = leaveInfoMapper.list(page, leaveInfoParam.getCondition(), null, userId, null, 2);
            //第三种情况
            //校级别登录也就是三级审批人，只要是状态为3的都把数据刷出来
            if (null == list2 || 0 == list2.size()) {
                list2 = leaveInfoMapper.list(page, leaveInfoParam.getCondition(), null, null, userId, 3);
            }
        } else {
            list2 = list;
        }
        return getLeaveInfoResults(list2);
    }

    //处理数据
    private List<LeaveInfoResult> getLeaveInfoResults(List<LeaveInfoPO> list) {
        List<LeaveInfoResult> leaveInfoResults = new ArrayList<>();
        Map<String, String> stuMap = convertList2MapForStu();
        list.forEach(leaveInfoPO -> {
            LeaveInfoResult leaveInfoResult = new LeaveInfoResult();
            BeanUtils.copyProperties(leaveInfoPO, leaveInfoResult);
            //请假类型划分
            //0--<3
            if (0 == leaveInfoPO.getLeaveInfoType()) {
                leaveInfoResult.setLeaveInfoTypeText("少于三天");
                //3<--1--<7
            } else if (1 == leaveInfoPO.getLeaveInfoType()) {
                leaveInfoResult.setLeaveInfoTypeText("超过三天少于一周");
                //2-->7
            } else {
                leaveInfoResult.setLeaveInfoTypeText("超过一周");
            }
            //请假人--学号
            leaveInfoResult.setLeaveUserName(leaveInfoPO.getLeaveUserNum() + "/" + stuMap.get(leaveInfoPO.getLeaveUserNum()));
            //状态转换
            if (0 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("待审批");
            } else if (1 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("已审批");
            } else if (2 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("院系领导审批中");
            } else if (3 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("校级领导审批中");
            } else if (4 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("已拒绝");
            } else if (6 == leaveInfoPO.getLeaveInfoStatus()) {
                leaveInfoResult.setLeaveInfoStatusText("已销假");
            } else {
                leaveInfoResult.setLeaveInfoStatusText("用户存档");
            }
            leaveInfoResults.add(leaveInfoResult);
        });
        return leaveInfoResults;
    }

    //所有学生
    public Map<String, String> convertList2MapForStu() {
        List<LeaveUserPO> list = stuManageService.list();
        return list.stream().collect(Collectors.toMap(LeaveUserPO::getLeaveUserNum, LeaveUserPO::getLeaveUserName));
    }

    //状态（0-待审批；1-已审批；2-院系领导审批中；3-校级领导审批中；4-已拒绝；5-用户存档 6-销假）
    public ResponseData approved(Long leaveInfoId, Integer type) {
        boolean b = false;
        String flag = null;
        List<String> logs = new ArrayList<>(8);
        Long userId = LoginContextHolder.getContext().getUserId();
        try {
            LeaveInfoPO leaveInfoPO = this.getOne(new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoId));
            //辅导员审批
            if (userId.longValue() == leaveInfoPO.getStairApprovalId().longValue()) {
                //辅导员刷出数据为type=0且status=0-----审批后status=1,此记录为已审批
                if (0 == leaveInfoPO.getLeaveInfoType() && 0 == leaveInfoPO.getLeaveInfoStatus()) {
                    //审批后status=1,此记录为已审批
                    if (1 == type) {
                        leaveInfoPO.setLeaveInfoStatus(1);
                        logs.add("已通过/4");
                    } else {
                        leaveInfoPO.setLeaveInfoStatus(4);
                        logs.add("已拒绝/4");
                    }
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                }
                // 辅导员刷出数据为type=1且status=0-----审批后status=2,此记录为院系领导审批中
                if (1 == leaveInfoPO.getLeaveInfoType() && 0 == leaveInfoPO.getLeaveInfoStatus()) {

                    leaveInfoPO.setLeaveInfoStatus(2);
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                    logs.add("辅导员已通过/4");
                    logs.add("院系领导审核中/5");
                }
                // 辅导员刷出数据为type=2且status=0-----审批后status=2,此记录为院系领导审批中
                if (2 == leaveInfoPO.getLeaveInfoType() && 0 == leaveInfoPO.getLeaveInfoStatus()) {
                    leaveInfoPO.setLeaveInfoStatus(2);
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                    logs.add("辅导员已通过/4");
                    logs.add("院系领导审核中/5");
                }
            }
            //院系领导审批
            if (userId.longValue() == leaveInfoPO.getFoxbaseApprovalId().longValue()) {
                //领导刷出数据为type=1且status=2-----审批后status=1,此记录为已审批
                if (1 == leaveInfoPO.getLeaveInfoType() && 2 == leaveInfoPO.getLeaveInfoStatus()) {
                    if (1 == type) {
                        leaveInfoPO.setLeaveInfoStatus(1);
                        logs.add("已通过/6");
                    } else {
                        leaveInfoPO.setLeaveInfoStatus(4);
                        logs.add("已拒绝/6");
                    }
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                }
                //领导刷出数据为type=2且status=2-----审批后status=3,此记录为校级领导审批中
                if (2 == leaveInfoPO.getLeaveInfoType() && 2 == leaveInfoPO.getLeaveInfoStatus()) {
                    leaveInfoPO.setLeaveInfoStatus(3);
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                    logs.add("院系领导已通过/6");
                    logs.add("校级领导审核中/7");
                }
            }
            //校级领导审批
            if (userId.longValue() == leaveInfoPO.getTertiaryApprovalId().longValue()) {
                if (2 == leaveInfoPO.getLeaveInfoType() && 3 == leaveInfoPO.getLeaveInfoStatus()) {
                    if (1 == type) {
                        leaveInfoPO.setLeaveInfoStatus(1);
                        logs.add("已通过/8");
                    } else {
                        leaveInfoPO.setLeaveInfoStatus(4);
                        logs.add("已拒绝/8");
                    }
                    this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
                }
            }
            b = writeHistory(logs, userId, leaveInfoId);
        } catch (Exception e) {
            flag = e.getMessage();
        }
        if (StringUtils.isEmpty(flag) && b) {
            return ResponseData.success(200, "操作成功", null);
        }
        return ResponseData.success(500, "操作失败", null);
    }

    public boolean writeHistory(List<String> logs, Long leaveApprovalPer, Long leaveInfoId) {
        boolean b = false;
        List<LeaveApprovalPO> leaveApprovalPOS = new ArrayList<>(logs.size());
        if (!CollectionUtils.isEmpty(logs)) {
            logs.forEach(s -> {
                String con = s.split("/")[0];
                String flg = s.split("/")[1];
                LeaveApprovalPO leaveApprovalPO = new LeaveApprovalPO();
                leaveApprovalPO.setLeaveApprovalRecord(con);
                leaveApprovalPO.setLeaveApprovalTime(System.currentTimeMillis());
                leaveApprovalPO.setLeaveApprovalPer(leaveApprovalPer);//审批人id
                leaveApprovalPO.setLeaveInfoId(leaveInfoId);//请假人id
                leaveApprovalPO.setLeaveApprovalTex(flg);
                leaveApprovalPOS.add(leaveApprovalPO);
            });
            b = leaveApprovalService.saveBatch(leaveApprovalPOS);
        }
        return b;
    }

    public List<LeaveInfoResult> getAllList(LeaveInfoParam leaveInfoParam) {

        Long userId = LoginContextHolder.getContext().getUserId();
        List<LeaveInfoPO> leaveInfoPOS = null;
        //用户填写搜索以及状态
        if (!StringUtils.isEmpty(leaveInfoParam.getCondition()) && !(null == leaveInfoParam.getLeaveFlag())) {
            QueryWrapper<LeaveInfoPO> leaveInfoPOQueryWrapper = new QueryWrapper<>();
            leaveInfoPOQueryWrapper.eq("leave_user_num", leaveInfoParam.getCondition());
            leaveInfoPOQueryWrapper.eq("leave_info_status", leaveInfoParam.getLeaveFlag());
            leaveInfoPOQueryWrapper.and(wrapper -> wrapper
                    .eq("stair_approval_id", userId).or().
                            eq("foxbase_approval_id", userId).or().
                            eq("tertiary_approval_id", userId));
            leaveInfoPOS = this.list(leaveInfoPOQueryWrapper);
            //用户填写搜索
        } else if (!StringUtils.isEmpty(leaveInfoParam.getCondition()) && (null == leaveInfoParam.getLeaveFlag())) {
            leaveInfoPOS = this.list(new QueryWrapper<LeaveInfoPO>().eq("leave_user_num", leaveInfoParam.getCondition())
                    .in("leave_info_status", 0, 1, 2, 3, 4, 6)
                    .and(wrapper -> wrapper
                            .eq("stair_approval_id", userId).or()
                            .eq("foxbase_approval_id", userId).or()
                            .eq("tertiary_approval_id", userId)));
            //用户填写状态
        } else if (StringUtils.isEmpty(leaveInfoParam.getCondition()) && !(null == leaveInfoParam.getLeaveFlag())) {
            leaveInfoPOS = this.list(new QueryWrapper<LeaveInfoPO>()
                    .eq("leave_info_status", leaveInfoParam.getLeaveFlag())
                    .and(wrapper -> wrapper
                            .eq("stair_approval_id", userId).or()
                            .eq("foxbase_approval_id", userId).or()
                            .eq("tertiary_approval_id", userId)));
        } else {
            //默认查询
            leaveInfoPOS = this.list(new QueryWrapper<LeaveInfoPO>()
                    .in("leave_info_status", 0, 1, 2, 3, 4, 6)
                    .and(wrapper -> wrapper
                            .eq("stair_approval_id", userId).or()
                            .eq("foxbase_approval_id", userId).or()
                            .eq("tertiary_approval_id", userId)));
        }
        return getLeaveInfoResults(leaveInfoPOS);
    }

    //销假
    public ResponseData destroy(Long leaveInfoId) {
        boolean b = false;
        LeaveInfoPO leaveInfoPO = this.getOne(new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoId));
        if (1 == leaveInfoPO.getLeaveInfoStatus()) {
            leaveInfoPO.setLeaveInfoStatus(6);
            b = this.update(leaveInfoPO, new QueryWrapper<LeaveInfoPO>().eq("leave_info_id", leaveInfoPO.getLeaveInfoId()));
        }
        if (b) {
            return ResponseData.success(200, "销假成功", null);
        }
        return ResponseData.success(500, "只有在已审批状态下可销假", null);
    }
}
